package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.LoginDTO;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDTO dto) {

        //参数校验   手机号和密码登录
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())){
            //根据手机号查询登录用户
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getPhone, dto.getPhone()));

            //判断用户是否存在
            if (apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "请检查手机号");
            }

            //密码校验
            String password = apUser.getPassword();
            String inputPwd = dto.getPassword();

            //md5  获取加盐加密密码
            String newPassword = DigestUtils.md5DigestAsHex((inputPwd + apUser.getSalt()).getBytes());

            //判断加密密码是否和数据库中的密码相等
            if (!password.equals(newPassword)){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "手机号或密码错误");
            }

            //密码校验通过  颁发token
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            //封装返回数据
            Map<String,Object> map =new HashMap<>();
            //将密码和盐 设置为空 安全起见
            apUser.setPassword("");
            apUser.setSalt("");

            map.put("token",token);
            map.put("user",apUser);

            return ResponseResult.okResult(map);
        }else {

            //设备登录  点击先看看 预览app
            if (dto.getEquipmentId()==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }

            //预览app  将当前用户id设置为0 获取token
            Map<String,Object> map =new HashMap<>();
            String token = AppJwtUtil.getToken(0L);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }

    }
}
